certusApp.service('CertusFormAjax', function ($cookies, $http) {
    var access_token = $cookies.get("access_token");
    var token_type = $cookies.get("token_type");
    var baseUrl = $cookies.get("baseUrl");
    var iprex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
    var baseIp = iprex.exec(baseUrl);
    var processInstanceId = "";
    var stepInstanceId = "";

    if (!isLogin(access_token)) {
        window.location.href = "login.html";
        return;
    }
    //authority 权限 存储
    //['RSZX-YGLBC%edit','RSZX-YGLBD%d cx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     e']   ---- needArr -- edit retrieve download delete
    //{
    //     'RSZX-YGLBC':editMet,
    //     'RSZX-YGLBD':deleteMet --方法名变量 原方法 直接取出 加双引号
    // }
    //usersColumns -- 原方法 content 内容  直接写成变量
    this.initOperateAutho = function (authority, needArr, methodArr, usersColumns) {
        var content = '';
        if (needArr) {
            for (var i in needArr) {
                var needs = needArr[i].split("%");
                if (authority[needs[0]]) {
                    if (needs[1] == "edit") {
                        var insert = methodArr[needs[0]];
                        content += '<button class="btn btn-xs btn-info" onclick="' + insert + '"><i class="fa fa-edit"></i>  编辑</button>';
                        content += '  ';
                    } else if (needs[1] == "delete") {
                        var insert = methodArr[needs[0]];
                        content += '<button class="btn btn-xs btn-danger" onclick="' + insert + '"><i class="fa fa-trash-o"></i>  删除</button>';
                        content += '  ';
                    } else if (needs[1] == "retrieve") {
                        var insert = methodArr[needs[0]];
                        content += '<button class="btn btn-xs btn-primary" onclick="' + insert + '"><i class="icon-eye-open"></i>  查看</button>';
                        content += '  ';
                    } else if (needs[1] == "download") {
                        var insert = methodArr[needs[0]];
                        content += '<button class="btn btn-xs btn-info" onclick="' + insert + '"><i class="icon-cloud-download"></i>  下载</button>';
                        content += '  ';
                    } else if (needs[1] == "upload") {
                        var insert = methodArr[needs[0]];
                        content += '<button class="btn btn-xs btn-success" onclick="' + insert + '"><i class="icon-cloud-upload"></i>  更新</button>';
                        content += '  ';
                    }
                }
            }
        }

        return content;
    }


    this.download = function (url, param) {
        window.location.href = baseUrl + url + "?access_token=" + access_token + "&" + param;
    };
    this.upload = function (url, form, successFunction) {
        $http({
            method: 'POST',
            url: baseUrl + url + "?access_token=" + access_token,
            data: form,
            headers: {'Authorization': token_type + " " + access_token, 'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(successFunction, function (error) {
            //console.log('upload fail');

            if (error && error.status) {
                debugger;
                var status = parseInt(error.status);
                if (status == 403) {
                    layer.msg("抱歉您暂时不能进行此项操作");
                    window.history.back();
                    layer.closeAll();
                    return;
                }
                // if (error.status == "400") {
                //     layer.closeAll();
                //     layer.msg(error.data);
                //     return;
                // }
                if (parseInt(status) == 401  || parseInt(status) == 400 || status == -1) {
                    layer.msg("非常抱歉，您已经退出登录，正在为您跳转。");
                    setTimeout(function(){
                        window.location.href = "login.html";
                    },2000);
                    return;
                }
                if(status == 405){
                    layer.msg(error.data);
                    layer.closeAll();
                    return;
                }
                if (status != 401) {
                    layer.msg(error.data);
                    layer.closeAll();
                    return;
                }
                if(status > 399){
                    layer.msg("非常抱歉，后台发生了一个很严重的错误,请联系管理员。");
                    layer.closeAll();
                    return;
                }
            }
            window.location.href = "login.html";
        })
    }
    this.ajax = function (url, param, successFunction) {
        if (parseInt(new Date().getTime() - parseInt($cookies.get("expiration"))) < 0) {

        } else {
            setCookie("access_token", "logout");
            setCookie("expires_in", "logout");
            setCookie("refresh_token", "logout");
            setCookie("token_type", "logout");
            window.location.href = "login.html";
        }
        var auth = token_type + " " + access_token;
        // $localStorage.put("token",auth);

        return $http({
            url: baseUrl + url + "?access_token=" + access_token,
            method: 'POST',
            data: param,
            dataType: "application/json",
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            transformRequest: function (obj) {
                //进行序列化，否则后台无法接收到参数
                var str = [];
                for (var p in obj) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
                return str.join("&");
            }
        }).then(successFunction, function (error) {
            debugger;
            if (error && error.status) {
                var status = parseInt(error.status);
                if (status == 403) {
                    layer.msg("抱歉您暂时不能进行此项操作");
                    window.history.back();
                    layer.closeAll();
                    return;
                }

                // if (error.status == "400") {
                //     layer.closeAll();
                //     layer.msg(error.data);
                //     return;
                // }
                if(status == 999){
                    layer.msg("非常抱歉，您已经退出登录，正在为您跳转。");
                    setTimeout(function(){
                        window.location.href = "login.html";
                    },2000);
                    return;
                }
                if (status == 401  || status == 400 || status == -1) {
                    layer.msg("非常抱歉，您已经退出登录，正在为您跳转。");
                    setTimeout(function(){
                        window.location.href = "login.html";
                    },2000);
                    return;
                }
                if(status == 405){
                    layer.msg(error.data);
                    return;
                }
                if (status != 401) {
                    layer.msg(error.data);
                    return;
                }
                if(status > 399){
                    layer.msg("非常抱歉，后台发生了一个很严重的错误,请联系管理员。");
                    return;
                }
            }
            window.location.href = "login.html";
        })
    };


    this.logout = function () {
        $http({
            url: baseUrl + "tokens/revoke?access_token=" + access_token,
            method: 'GET',
            headers: {
                'Authorization': token_type + " " + access_token,
                // 'Accept': '*/*',
                // 'Content-Type': 'application/json'
            }
        }).then(function (response) {
            window.location.href = "login.html";
        }, function (error) {
            window.location.href = "login.html";
        })
        setCookie("access_token", "logout");
        setCookie("expires_in", "logout");
        setCookie("refresh_token", "logout");
        setCookie("token_type", "logout");

    }
    return this;
});
certusApp.service('CertusJsonAjax', function ($cookies, $http) {
    var access_token = $cookies.get("access_token");
    var token_type = $cookies.get("token_type");
    var baseUrl = $cookies.get("baseUrl");
    // var iprex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
    var baseIp = baseUrl
    if (baseIp.indexOf("111.46:18080/") > -1) {
        baseIp = "172.16.3.247"
    } else if (baseIp.indexOf("localhost") > -1) {
        baseIp = "localhost";
    }else if(baseIp.indexOf("67.42:8080") > -1){
        baseIp = "172.16.83.90";
    }else if(baseIp.indexOf("83.90:8080") > -1){
        baseIp = "172.16.83.90";
    }else if(baseIp.indexOf("83.90:9090") > -1){
        baseIp = "172.16.3.246";
    } else {
        baseIp = "172.16.3.58"
    }
    var processInstanceId = "";
    var stepInstanceId = "";
    var wkstepName = "";
    var baseAuthority = {};

    this.setWorkflowInfo = function (processInstanceIdte, stepInstanceIdte, wkStepName) {
        processInstanceId = processInstanceIdte;
        stepInstanceId = stepInstanceIdte;
        wkstepName = wkStepName;
    }



    $.ajax({
        url: baseUrl + 'baseAuthority' + "?access_token=" + access_token,
        type: 'POST',
        crossDomain: true,
        cache: false,
        data: {},
        async: false,
        processData: false,
        contentType: "application/json",
        dataType: "json",
        headers: {
            'Authorization': token_type + " " + access_token
        }
    }).done(function (res) {
        baseAuthority = res;
    }).fail(function (res, a, b, c) {
    });

    this.setBaseAuthority = function (authoritys) {
        baseAuthority = authoritys;
    }

    this.initBaseAuthority = function (scope) {
        ;
        scope.autho = baseAuthority;
    }

    this.getProInstanceId = function () {
        if (processInstanceId != "") {
            return processInstanceId;
        } else {
            layer.msg("页面错误");
        }
    }

    this.getWkStepName = function () {
        if (wkstepName != "") {
            return wkstepName;
        } else {
            layer.msg("页面错误");
        }
    }

    this.getStepInstanceId = function () {
        if (stepInstanceId != "") {
            return stepInstanceId;
        } else {
            layer.msg("页面错误");
        }
    }

    if (!isLogin(access_token)) {
        window.location.href = "login.html";
        return;
    }

    this.dataInit = function (url, param, proColumns, gridId, toolId, pageSize, pageArr) {
        if (!pageSize) {
            pageSize = 10;
        }
        if (!pageArr) {
            pageArr = [5, 10, 15, 20]
        }
        var proOption = {
            lang: 'zh-cn',
            ajaxLoad: true,
            extraWidth: 20,
            // loadAll : true,
            loadURL: baseUrl + url,
            exportFileName: '项目列表',
            // datas: eval("(" + result.data + ")"),
            columns: proColumns,
            gridContainer: gridId,
            toolbarContainer: toolId,
            tools: '',
            pageSize: pageSize,
            pageSizeLimit: pageArr
        };
        var proGrid = $.fn.dlshouwen.grid.init(proOption);
        if (param != null) {
            proGrid.parameters = param;
            proGrid.refresh(true);
            return proGrid;
        } else {
            proGrid.load();
            return proGrid;
        }
    }

    this.initDataGrid = function (proColumns, gridId, toolId, data) {
        var proOption = {
            lang: 'zh-cn',
            ajaxLoad: false,
            extraWidth: 20,
            loadAll : true,
            // loadURL: baseUrl + url,
            exportFileName: '项目列表',
            datas: data,
            columns: proColumns,
            gridContainer: gridId,
            toolbarContainer: toolId,
            tools: ''
        };
        var proGrid = $.fn.dlshouwen.grid.init(proOption);
        proGrid.load();
    }

    this.ajaxNode = function (module, url, param, successFunction) {

        var socket = io(baseIp + ":9001" + "/" + module);
        // var socket = io("localhost:9000");
        socket.on("connect", function (msg, b, c) {

        })
        socket.on("message", function (data, b, c) {
            if (data && data == "success connect") {
                if (param) {
                    param.headerAuthorization = access_token;
                }
                socket.emit(url, param);
            } else if (data) {
                socket.close();
                successFunction(data);
            }
        })
    };

    this.socketNode = function (module, url, successFunction) {

        var socket = io(baseIp + ":9001" + "/" + module);
        // var socket = io("localhost:9000");
        successFunction(socket);
        return socket;
    };

    this.ajax = function (url, param, successFunction) {
        if (parseInt(new Date().getTime() - parseInt($cookies.get("expiration"))) < 0) {

        } else {
            setCookie("access_token", "logout");
            setCookie("expires_in", "logout");
            setCookie("refresh_token", "logout");
            setCookie("token_type", "logout");
            window.location.href = "login.html";
        }
        var auth = token_type + " " + access_token;
        // $localStorage.put("token",auth);
        // layer.msg('正在处理，请稍后，谢谢...', {icon: 16,shade: [0.5, '#f5f5f5'],scrollbar: false,offset: '200px',time: 0});
        $http({
            url: baseUrl + url + "?access_token=" + access_token,
            method: 'POST',
            data: param,
            dataType: "application/json",
            headers: {
                'Authorization': token_type + " " + access_token
            }
        }).then(successFunction, function (error) {
            debugger;
            if (error && error.status) {
                debugger;
                var status = error.status;
                if (status == 403) {
                    layer.msg("抱歉您暂时不能进行此项操作");
                    window.history.back();
                    layer.closeAll();
                    return;
                }

                // if (error.status == "400") {
                //     layer.closeAll();
                //     layer.msg(error.data);
                //     return;
                // }
                if(status == 999){
                    layer.msg("非常抱歉，您已经退出登录，正在为您跳转。");
                    setTimeout(function(){
                        window.location.href = "login.html";
                    },2000);
                    return;
                }
                if (status == 401  || status == 400 || status == -1) {
                    layer.msg("非常抱歉，您已经退出登录，正在为您跳转。");
                    setTimeout(function(){
                        window.location.href = "login.html";
                    },2000);
                    return;
                }
                if (status == 405) {
                    layer.msg(error.data);
                    return;
                }
                if (status != 401) {
                    layer.msg(error.data);
                    return;
                }
                if(status > 399){
                    layer.msg("非常抱歉，后台发生了一个很严重的错误,请联系管理员。");
                    return;
                }
            }
            window.location.href = "login.html";
        })
    };
    this.logout = function () {
        $http({
            url: baseUrl + "tokens/revoke?access_token=" + access_token,
            method: 'GET',
            headers: {
                'Authorization': token_type + " " + access_token,
            }
        }).then(function (response) {
            window.location.href = "login.html";
        }, function (error) {
            window.location.href = "login.html";
        })
        setCookie("access_token", "logout");
        setCookie("expires_in", "logout");
        setCookie("refresh_token", "logout");
        setCookie("token_type", "logout");
    }
    return this;
});


certusApp.controller('ModalInstanceCtrl', function ($scope, $modalInstance, data, CertusJsonAjax) {
    $scope.modalContent = data.modalContent;
    $scope.ok = function () {
        $modalInstance.close(); // 点击确认后关闭弹窗
    };
    $$scope.ok = function () {
        $modalInstance.close(); // 点击确认后关闭弹窗
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel'); // 点击取消后撤销模态框
    }
    $scope.downLoad = function (a) {
    }

});

certusApp.controller('ModalInstanceCtrl1', function ($scope, $modalInstance, data, CertusJsonAjax) {
    $$scope = $scope;
    $scope.modalContent = data.modalContent;
    $scope.ok = function () {
        $modalInstance.close(); // 点击确认后关闭弹窗
    };
    $$scope.ok = function () {
        $modalInstance.close(); // 点击确认后关闭弹窗
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel'); // 点击取消后撤销模态框
    }
    $scope.startExitSub = function (a) {
        if(certusValidateNotnullPolyfill()){
            $CertusJsonAjax.ajax("startExitUser",$scope.modalContent,function(res){
                if(res.data == "success"){
                    layer.msg("离职成功");
                    $modalInstance.close();
                    dataInit.refresh(true);
                }else if(res.data == "dont"){
                    layer.msg("人员不存在")
                }else if(res.data == "failed"){
                    layer.msg("离职失败")
                }
            })
        }
    }
    ;
    var picker1 = $('#datetimeid').datetimepicker({
        format: 'YYYY-MM-DD',
        locale: moment.locale('zh-cn'),
        //minDate: '2016-7-1'
    })

});

certusApp.factory('fileListService', function ($modal, $q, $log) {
    return {
        openConfirmWindow: function ($scope, modalContent) {
            var deferred = $q.defer();//生成deferred异步对象
            var modalInstance = $modal.open({
                templateUrl: 'proinfo/edit/edit-bid-fileList.html',
                controller: 'ModalInstanceCtrl',
                size: 'sm', //尺寸
                resolve: {
                    data: function () {
                        return {modalContent: modalContent};
                    }
                }
            });
            modalInstance.result.then(function () {
                if (!!modalInstance) {
                    modalInstance.dismiss('cancel');
                }
                deferred.resolve();
            }, function () {
                $log.info('Modal dismissed at: ' + new Date())
            });
            return deferred.promise;
        }
    }
});

certusApp.factory('addExitModal', function ($modal, $q, $log) {
    return {
        openConfirmWindow: function ($scope, modalContent) {
            var deferred = $q.defer();//生成deferred异步对象
            var modalInstance1 = $modal.open({
                templateUrl: 'exit/add/addexit.html',
                controller: 'ModalInstanceCtrl1',
                size: 'sm', //尺寸
                resolve: {
                    data: function () {
                        return {modalContent: modalContent};
                    }
                }
            })
            modalInstance1.opened.then(function () { //打开模态框时需要执行的事件
                ;
                console.log('modal is opened');
            });
            modalInstance1.result.then(function () {
                ;
                if (!!modalInstance1) {
                    modalInstance1.dismiss('cancel');
                }
                deferred.resolve();
            }, function () {
                $log.info('Modal dismissed at: ' + new Date())
            });
            return deferred.promise;
        }
    }
});

certusApp.factory('backlogPersonList', function ($modal, $q, $log) {
    return {
        openConfirmWindow: function ($scope, modalContent) {
            var deferred = $q.defer();//生成deferred异步对象
            var modalInstance = $modal.open({
                templateUrl: 'proinfo/edit/list-backlog-person.html',
                controller: 'ModalInstanceCtrl',
                size: 'sm', //尺寸
                resolve: {
                    data: function () {
                        return {modalContent: modalContent};
                    }
                }
            });
            modalInstance.result.then(function () {
                if (!!modalInstance) {
                    modalInstance.dismiss('cancel');
                }
                deferred.resolve();
            }, function () {
                $log.info('Modal dismissed at: ' + new Date())
            });
            return deferred.promise;
        }
    }
});

certusApp.factory('projProportion', function ($modal, $q, $log) {
    return {
        openConfirmWindow: function ($scope, modalContent,$CertusJsonAjax) {
            var deferred = $q.defer();//生成deferred异步对象
            var modalInstance = $modal.open({
                templateUrl: 'proinfo/edit/projProportion.html',
                controller: 'ModalInstanceCtrl',
                size: 'sm', //尺寸
                resolve: {
                    data: function () {

                        return {modalContent: modalContent};
                    }
                }
            });
            modalInstance.result.then(function () {
                if (!!modalInstance) {
                    modalInstance.dismiss('cancel');
                }
                deferred.resolve();

            }, function () {
                $log.info('Modal dismissed at: ' + new Date())
            });
            return deferred.promise;
        }
    }
});

